package com.`as`.common

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Parcelable
import androidx.core.app.ActivityCompat

/**
 * descrition:Activity 相关
 */
/**
 * 判断当前Activity是否关闭
 * @param pkg The name of the package.
 * @param cls The name of the class.
 * @return `true`: yes<br></br>`false`: no
 */
@SuppressLint("QueryPermissionsNeeded")
fun isActivityExists(
    pkg: String,
    cls: String,
    context:Context,
): Boolean {
    val intent = Intent()
    intent.setClassName(pkg, cls)
    val pm: PackageManager = context.packageManager
    return !(pm.resolveActivity(
        intent,
        0
    ) == null || intent.resolveActivity(pm) == null || pm.queryIntentActivities(
        intent,
        0
    ).size == 0)
}

/**
 * 启动一个Activity
 *
 * @param cls     The activity class.
 * @param arg
 */
fun Context.mStartActivity(cls: Class<*>, vararg arg: Pair<String, *>) {
    val i = Intent(this, cls)
    arg.forEach {
        when (val value = it.second) {
            is String -> i.putExtra(it.first, value)
            is Int -> i.putExtra(it.first, value)
            is Float -> i.putExtra(it.first, value)
            is Boolean -> i.putExtra(it.first, value)
            is Parcelable -> i.putExtra(it.first, value)
//            else -> i.putExtra(it.first, Gson().toJson(value))
        }
    }
    startActivity(i)
}

/**
 * Start the activity.
 *
 * @param intent   The description of the activity to start.
 */
fun Context.mStartActivity(
    intent: Intent
) {
    startActivity(intent)
}

fun Context.mStartActivityForResult(cls: Class<*>, requestCode: Int) {
    ActivityCompat.startActivityForResult(this as Activity, Intent(this, cls), requestCode, null)
}

/**
 * Start home activity.
 * 回到桌面
 */
fun Context.startHomeActivity() {
    val homeIntent = Intent(Intent.ACTION_MAIN)
    homeIntent.addCategory(Intent.CATEGORY_HOME)
    homeIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    startActivity(homeIntent)
}


/**
 * 判断Activity是否存活
 *
 * @param activity The activity.
 * @return `true`: yes<br></br>`false`: no
 */
fun isActivityAlive(activity: Activity?): Boolean {
    return (activity != null && !activity.isFinishing
            && (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 || !activity.isDestroyed))
}

/**
 * Finish the activity.
 *
 * @param activity The activity.
 */
fun Context.finishActivity(activity: Activity) {
    finishActivity(activity)
}


